
package com.joysuch.wwyt.core.common.util;

import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class NumberUtils {

    public static void main(String[] args) {
        System.out.println(keepDigits(0, 2));
        System.out.println(keepDigits(0.1, 2));
        System.out.println(keepDigits(0.01, 2));
        System.out.println(keepDigits(0.001, 2));
        System.out.println(keepDigits(0.0001, 2));
        System.out.println(keepDigits(1, 2));
        System.out.println(keepDigits(1.0, 2));
        System.out.println(keepDigits(1.01, 2));
        System.out.println(keepDigits(1.001, 2));
        System.out.println(keepDigits(1.0001, 2));
    }

    public static String keepDigits(double value, int digits) {
        Assert.isTrue(digits > 0, "位数必须大于等于0");
        return new BigDecimal(value).setScale(digits, RoundingMode.HALF_UP).toString();
//        String temp = Math.round(Math.pow(10, digits) * value) + "";
//        temp = temp.substring(0, temp.length() - digits) + "." + temp.substring(temp.length() - digits);
//        while (digits > 0) {
//            if (temp.charAt(temp.length() - 1) == '0') {
//                temp = temp.substring(0, temp.length() - 1);
//            } else {
//                break;
//            }
//            digits--;
//        }
//        if (temp.endsWith(".")) {
//            temp = temp.substring(0, temp.length() - 1);
//        }
//        return temp;
    }

}
